<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/9/6
 * Time: 11:03
 */

namespace Biz\module\Classes\adm;

use Biz\model\activity\OutCouponConfig as mOutCouponConfig;
use Biz\validate\activity\OutCoupon as vOutCoupon;

class OutCoupon extends \Biz\module\Classes\OutCoupon
{
    public static function getSearchList($where, $limit)
    {

        $list = mOutCouponConfig::select('*', ['ORDER'=>['id'=>'DESC'],'LIMIT' => $limit]);

        $list = array_map(function ($v) {
            mOutCouponConfig::formatInfo($v);

            return $v;
        }, $list);

        return $list;

    }

    public static function changeStatus($id, $status)
    {

        $ret = mOutCouponConfig::changeStatus($id, $status);

        self::cacheOutCoupon($id);

        return $ret;
    }

    public static function saveData($data, $templates = [])
    {
        $moduleMap = [
            'pic'    => '图片模块',
            'mobile' => '手机模块'
        ];

        $scenes = empty($data['id']) ? 'create' : 'update';

        if (!vOutCoupon::validate($data, $scenes)) {
            $msg = vOutCoupon::firstError();
            throw new \Exception($msg);
        }

        $templateData = [];

        foreach ($templates as $module => $template) {
            if (empty($template)) {
                throw new \Exception('请正确提交页面模块，至少有一个图片模块和一个手机号 模块');
            }
            foreach ($template as $key => $value) {
                if (!vOutCoupon::validate($value, $scenes . '_' . $module)) {
                    $msg = vOutCoupon::firstError();
                    throw new \Exception(sprintf("请检查第%d处的%s，出现错误：%s", $key, $moduleMap[$module], $msg));
                }

                $templateData[] = array_merge(['type' => $module], $value);
            }
        }

        $sortWeight = array_column($templateData, 'weight');

        array_multisort($sortWeight, SORT_DESC, SORT_NUMERIC, $templateData);

        $data['template_config'] = json_encode($templateData, JSON_UNESCAPED_UNICODE);


        $id = mOutCouponConfig::createOrEdit($data['id'], $data);

        self::cacheOutCoupon($id);



        return $id;


    }
}